package com.sptpc.demo1.controller;

import com.sptpc.demo1.controller.requests.AddOrderRequest;
import com.sptpc.demo1.controller.requests.PutOrderRequest;
import com.sptpc.demo1.model.Order;
import com.sptpc.demo1.controller.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j  //日志
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private IOrderService orderService;

    /**
     * 下订单 传递参数姓名和饮品id
     * @param request
     * @param bindingResult
     * @return
     */
    @PostMapping("/")
    public Order addNewOrder(@RequestBody AddOrderRequest request, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            for (ObjectError error : bindingResult.getAllErrors()) {
                log.error(error.toString());
            }
            return null;
        }else {
            log.info("订单信息:{}",request);

            Order order=new Order();
            BeanUtils.copyProperties(request,order);
            orderService.addOrder(order,request.getItems());
            return order;
        }
    }


    @PutMapping("/")
    public Order modifyOrder(@RequestBody PutOrderRequest orderRequest){
        log.info("传递参数：{}"+orderRequest);
        Order order1=orderService.getIdOrder(orderRequest.getId());
        order1.setState(orderRequest.getState());
        orderService.updateOrder(order1);
        return order1;
    }

    @DeleteMapping("/{id}")
    public String delete(@PathVariable Integer id){
        log.info("删除id：{}"+id);
        orderService.dleteOrder(id);
        return "删除成功";
    }

    /**
     * 姓名搜索订单
     * @param customer
     * @return
     */
    @GetMapping("/{customer}")
    public List<Order> getOrdersByCustomer(@PathVariable String customer){
        List<Order> list=orderService.getOrderByCustomer(customer);
        return list;
    }
}
